package com.aebiz.usercenter.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aebiz.usercenter.common.util.ConstatFinalUtil;
import com.aebiz.usercenter.common.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 需要登录的servlet
 * @author zhangshizhu
 *
 */
public class AuthFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("=========doFilter=======");
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) resp;
		HttpSession session=request.getSession();
		
		/*先检查session是否有值*/
        JSONObject adminsJSON=(JSONObject) session.getAttribute("admins");
    	/*	if(adminsJSON!=null){
			chain.doFilter(request, response);
			return;
		}*/
		/* token
		 * 如果有多个token:
		 * 取最后一个
		 *  */
		String[] tokens=request.getParameterValues("token");
		String token="";
		if(tokens!=null)
		{
			token=tokens[tokens.length-1];
		}
		/* 传入了token
		 * 就是从用户中心跳转过来的
		 *  */
		if(!"".equalsIgnoreCase(token)){
			/* 到token的颁发中心,去验证一下是不是你颁发的
			 * 验证token的接口
			 *  */
			HttpUtil httpUtil = new HttpUtil() ;
			/**
			 * 拼装上行参数
			 * */
			JSONObject requestJSON=new JSONObject();
			requestJSON.put("version", "1");
			
			JSONObject dataJSON=new JSONObject();
			dataJSON.put("token", token);
			requestJSON.put("data", dataJSON);
			String url = ConstatFinalUtil.CONFIG_JSON.getString("userscenter.back.verifyToken.url");
			String params = "?json=" + requestJSON.toJSONString() ;
			url += params ;
			System.out.println("-----url----------" + url);
			String result = httpUtil.methodGet(url);
			System.out.println("======result========"+result + "==============");
			
			/**
			 * 处理返回值
			 * 解析成json格式
			 */
			JSONObject resultJSON=(JSONObject) JSON.parse(result);
			if(resultJSON!=null&&"0".equalsIgnoreCase(resultJSON.getString("code")+""))
			{
				JSONObject dataResJSON=(JSONObject) resultJSON.get("data");
				adminsJSON = (JSONObject) dataResJSON.get("admins");
				/*
				 * 将token的相关信息存储到客户端的session中
				 * */
				session.setAttribute("admins", adminsJSON);
				chain.doFilter(request, response);
				return ;
			}
		}
			/* 需要登陆
			 * 获取当前访问的URL
			 * 客户端跳转到用户中心的登陆页面,
			 * 把returnUrl带上,同时要加密哟(UrlEncode)
			 *  */
			String returnUrl = request.getRequestURL() + ""; 
			String queryStr = request.getQueryString() ; 
			/*?后面的参数木有了,
			 * 如何获取呢? 
			 * */
			if(queryStr != null)
			{
				returnUrl += "?" + queryStr ; 
			}
			System.out.println("=====returnUrl==========" + returnUrl);
			/*
			 * 客户端中转到用户中心
			 * http://xxxx:8080/userscenter-back/login.htm?returnUrl
			 * */
			String urls = ConstatFinalUtil.CONFIG_JSON.getString("userscenter.back.login.url") ;
			urls += "&returnUrl=" + URLEncoder.encode(returnUrl,"UTF-8") ; 
			System.out.println("=====urls========" + urls);
			response.sendRedirect(urls);

 	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

}
